package handle

import (
	"google.golang.org/protobuf/proto"
	. "leaf/common"
	"leaf/core/cluster"
	. "leaf/core/error"
	"leaf/core/gate"
	. "leaf/core/msg"
	"leaf/model"
	"leaf/pb"
)

func StartMatchHandler(agent gate.Agent, msg *PMsg) *Error {
	gamer, ok := agent.UserData().(*model.Gamer)
	if !ok {
		return Error_DBErr
	}

	userModel := gamer.GetUserModel()
	if userModel == nil {
		return Error_DBErr
	}

	var statusModel = gamer.GetStatusModel()
	if statusModel == nil {
		return Error_DBErr
	}

	server := cluster.GetBestNode(ServType_Match)
	if server == nil {
		return Error_DBErr
	}

	request := &pb.L2M_StartMatch{}
	request.Type = proto.Int32(1)
	request.User = userModel.User
	reply := &pb.M2L_StartMatch{}

	var err = server.Call("StartMatch", request, reply)
	if err != nil {
		return ConvertError(err)
	}

	//save model
	statusModel.Status.Mid = proto.Int32(server.ServerId)
	statusModel.Save()

	return Error_OK
}
